#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：pythonProject2 
@File    ：flask_use_id_new.py
@Author  ：beibei
@Date    ：2023/12/27 8:17 PM 
'''
from flask import Flask, request, jsonify
import redis
import json

app = Flask(__name__)

# Configure Redis connection
redis_conn = redis.Redis(
    host='127.0.0.1',
    port=6379,
    db=0,
    password='8948lulu'  # Replace with your Redis password
)


@app.route('/push', methods=['POST'])
def push_message():
    data = request.json
    userId = data['userId']
    message = data['data']
    user_msg = {'userId': userId, 'data': message}

    redis_conn.set(userId, json.dumps(user_msg), ex=300)
    return jsonify({'msg': 'Message pushed'}), 200


@app.route('/pull', methods=['GET'])
def pull_message():
    userId = request.args.get('userId')

    redis_res = redis_conn.get(userId)
    if redis_res is not None:
        return jsonify(json.loads(redis_res.decode('utf-8'))), 200
    else:
        return jsonify({'msg': 'No message found for the user'}), 404


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8999, debug=True)
